function setupPsychTestRig()
%introduce initial setup menu - import, export, run
%needs cleaning up. Could wrap everything in a try..catch, and throw an
%error within each block, to save having to reduplicate error messaging.
%
%Only save changes at end???? (i.e. have a temp intermediate struct.


    %print welcome message to console
    cloutput('')
    cloutput('%line')
    cloutput('Welcome to the PsychTestRig setup.')
    input('press RETURN to begin (or press ctrl+c to abort)\n');
    
    
    %clear any existing setup. Prompt for confirmation if necessary 
    clearSetup();
    

    %--------------------
    % ######   1   ######
    %--------------------
    cloutput('1. We begin by running a few diagnostic tests on your system')
    input('press RETURN to continue\n');
    errCode=local_runDiagnostic();
    if (errCode==3)
        error('script terminated: Diagnostic failed.')
    elseif(errCode==1)
        cloutput('/*****Warning: Some aspects of your system have not been tested with PsychTestRig. It may not operate normally.*****/')
    end
    cloutput('');

    %--------------------
    % ######   2   ######
    %--------------------
    cloutput('2. Next you must a home directory in which all your experiments will be stored (e.g. "C:\My Documents\Experiments")')
    input('press RETURN to continue\n');
    directory_name = uigetdir(cd,'Please select the directory which you would like to use as your home directory. This is where all your experiments will be stored (e.g. "C:\My Documents\Experiments").');
    if (directory_name==0)
        error('script terminated by user')
    else
        setPrefVal('homeDir',directory_name);
    end
    cloutput(['   HomeDir: ' directory_name '\n'])

    cloutput('2b. A backup directory in which copies of all your experimental data will be stored (e.g. "D:\MyBackups")')
    input('press RETURN to continue\n');
    directory_name = uigetdir(cd,'Please select the directory which you would like to use as your backup directory.');
    if (directory_name==0)
        error('script terminated by user')
    else
        setPrefVal('backupDir',directory_name);
    end
    cloutput(['   BackupDir: ' directory_name '\n'])
        
    %--------------------
    % ######   3   ######
    %--------------------
    cloutput('3. Do you wish to run in full mode (f) or lite mode (l) ? (In Lite mode databases are not used, which precludes advanced functionality)')
    mode=get1ofMInput('input "f" or "l" and press ENTER to continue: ',{'f','l'});
    mode=regexprep(mode,{'l', 'f'},{'lite','full'});
    setPrefVal('mode',mode);
    cloutput(['\n   mode: ' getpref('PsychTestRig_prefs','mode') '\n'])
     
    if (strcmpi(mode,'full'))
        
        cloutput('   Checking database prerequisites...')
        %Check that mysql.m present
        fprintf('      MYSQL.M..........      ')
        if exist('mysql.m','file')
            fprintf(['Found' ' [OK]\n'])
        else
            fprintf(['Not Found' ' [FAIL]\n'])
            error('PsychTestRig:setupPsychTestRig:toolkitNotFound','Script Terminated. "mysql.m" not found.\n\nPlease download Robert Almgren''s mysql-matlab package. This should be available at:\n   http://www.mathworks.com/matlabcentral/fileexchange/8663-mysql-database-connector\nYou may be able to find help on using this package at these sites:\n   http://www.mmf.utoronto.ca/resrchres/mysql/\n   http://www.courant.nyu.edu/~almgren/mysql/\n\nIf you have already download this package then you may need to make it visible to matlab.\nDo this by adding the containing directory to the search path (e.g. File => Set Path => Add folder...)') 
        end
        %Check that mysql.mex present (i.e. is compiled
        fprintf('      MYSQL.MEX........      ')
        try
            msg=mysql('status');
        catch
            fprintf(['Not Found' ' [FAIL]\n'])
            if (findstr('Attempt to execute SCRIPT mysql as a function', lasterr)) %try and provide some more info if possible
                myErr = lasterr;
                myErr = regexprep(myErr,'\\','\\\\'); %escape any backslash fileseps
                myErr = [myErr '\n\nScript Terminated. "mysql.m" was found, but it has not been compiled to MEX form. You may be able to find help on how to compile this package at these sites:\n   http://www.mmf.utoronto.ca/resrchres/mysql/\n   http://www.courant.nyu.edu/~almgren/mysql/'];
                error(myErr, 'x')
            end   
        end
        fprintf(['Found' ' [OK]\n'])
        cloutput('   ...Success!\n')
        
        %close any/all existing connections (???)
        mysql('closeall')    
        
        %--------------------
        % ######   3b   ######
        %--------------------
        %Check that server reachable
        cloutput('3b. Since you have selected FULL mode, we will now attempt to connect to your MySQL server. Remember, if the server is installed on this machine then the host is "localhost". If you do not know your username then try using "root"\n');
        retries=0;
        while (1)
            host=getStringInput('   host: ',true,true);
            username=getStringInput('   username: ',true,true);
            password=getStringInput('   password: ',true,true);
            try
                fprintf('\n      ');
                msg=mysql_connect(host,username,password);
                break
            catch
                cloutput(['      ...Connection failed!: ' lasterr '\n']) % don't allow a fatal error to be thrown
            end
            
            retries = retries + 1;
            if (retries==3)
                error('Script Terminated. Database authentication failed.') 
            end
        end
        cloutput('      ...Success!\n')
        
        %Save authentication info
        dbInfo.host = host;
        dbInfo.username = username;
        if (getBooleanInput('Would you like PsychTestRig to remember this password? (y/n) [n.b. this is not secure!!!] '))
            dbInfo.password = password;
        end
     	setPrefVal('dbInfo',dbInfo);

        
        %check that Mysql is the right version
        cloutput('\n   Checking server properties...')
        fprintf('      MySQL ver........      ')
        ver=mysql('SELECT VERSION()');
        if ~mysql_isAtLeastVersion(5,0,2) 
            fprintf([char(ver) ' [FAIL]\n'])
            error('Script Terminated: Please install MySQL version 5.0.2 or above.')
        else
            fprintf([char(ver) ' [OK]\n'])
        end
        cloutput('   ...Success!\n')
            
   
        %--------------------
        % ######   3c   ######
        %--------------------
        cloutput('3c. We will now ensure that the right data structures are present');
        input('press RETURN to continue\n');
        %Ensure db exists
        cloutput('   Connecting to database "psych_test_rig"...')
        try
            mysql_checkDatabaseExists('psych_test_rig', 'CREATE DATABASE psych_test_rig')
        catch
            cloutput('\n/*****script terminated: Database configuration failed (error in database).*****/')
            mysql('close')
            rethrow(lasterror)
        end
        cloutput('   ...Success!\n')
        
        %Connect to db
        msg=mysql('use psych_test_rig');
        
        %Verify tables
        cloutput('   Checking tables...')
        try
            local_checkTables();
        catch
            cloutput('\n/*****script terminated: Database configuration failed (error in tables).*****/')
            mysql('close')
            rethrow(lasterror)
        end
        cloutput('   ...Success!\n')
        
        mysql('close')
        
        %synchronise database with file structure
        synchDatabase('indent',3);
        
        
        
        
    end

   	cloutput('\n\nSetup complete!\nFor more information no what to do next type PsychTestRig')
	cloutput('%line')
    cloutput('')
    
end


%%%%%%%%%%%%%%%%%%%%%%%
%%% LOCAL FUNCTIONS %%%
%%%%%%%%%%%%%%%%%%%%%%%

function errCode=local_runDiagnostic()
%return 2 for fail, 1 for untested, 0 for OK.    
    fail=0;
    untested=0;
    
    %check matlab version
    fprintf('   Matlab version...      ')
    matver = getversion();
    if (matver < 7.4)
        fail=1;
        fprintf([num2str(matver) ' [FAIL]\n'])
    else
        fprintf([num2str(matver) ' [OK]\n'])
    end
 
    %check OS
    fprintf('   OS...............      ')
    if ispc
        fprintf(['PC' ' [OK]\n'])
    elseif isunix
        untested=1;
        fprintf(['UNIX' ' [UNTESTED]\n'])
    else
        untested=1;
        fprintf(['unknown' ' [UNTESTED]\n'])
    end
    
    if (fail)
        errCode=2;
    elseif(untested)
        errCode=1;
    else
        errCode=0;
    end
end


function err=local_checkTables()
    err=0;
    
    %Check "experiments"
    cloutput('   |    Checking table "experiments"...')
    creationText='CREATE TABLE experiments (id_num INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(32) NOT NULL UNIQUE, last_update TIMESTAMP, creation_date datetime NOT NULL default "1900-01-01 00:00:00", status varchar(32) NOT NULL default "PENDING", notes mediumtext)';
    triggerText='CREATE TRIGGER experiments_updateDate BEFORE INSERT ON experiments FOR EACH ROW BEGIN IF NEW.creation_date = "1900-01-01 00:00:00" THEN SET NEW.creation_date = NOW(); END IF; END'; %to automatically initialise creation_date        
    try
    	mysql_checkTableExists('experiments',creationText,triggerText);
    	mysql_checkFieldStructure('experiments','id_num','int(11)','null','NO','key','PRI','extra','auto_increment'); %,'creationText','ALTER TABLE experiments ADD id_num VARCHAR(32) NOT NULL AUTO_INCREMENT PRIMARY KEY'
    	mysql_checkFieldStructure('experiments','name','varchar(32)','null','NO','key','UNI'); %,'creationText','ALTER TABLE experiments ADD name VARCHAR(32) NOT NULL UNIQUE AFTER id_num'
    	mysql_checkFieldStructure('experiments','last_update','timestamp','null','NO','default','CURRENT_TIMESTAMP','extra','on update CURRENT_TIMESTAMP'); %,'creationText','ALTER TABLE experiments ADD name VARCHAR(32) NOT NULL UNIQUE AFTER name'
    	mysql_checkFieldStructure('experiments','creation_date','datetime','null','NO','default','1900-01-01 00:00:00');
    	mysql_checkFieldStructure('experiments','status','varchar(32)','null','NO','default','PENDING');
    	mysql_checkFieldStructure('experiments','notes','mediumtext','creationText','ALTER TABLE experiments ADD notes MEDIUMTEXT');
    catch
        rethrow(lasterror) %nothing more to add
    end

    %Check "participants"
    cloutput('   |    Checking table "participants"...')
    creationText='CREATE TABLE participants (id_num INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(32) NOT NULL UNIQUE, last_update TIMESTAMP, creation_date datetime NOT NULL default "1900-01-01 00:00:00", notes mediumtext, private_comments mediumtext)';
    triggerText='CREATE TRIGGER participants_updateDate BEFORE INSERT ON participants FOR EACH ROW BEGIN IF NEW.creation_date = "1900-01-01 00:00:00" THEN SET NEW.creation_date = NOW(); END IF; END'; %to automatically initialise creation_date        
    try
        mysql_checkTableExists('participants',creationText,triggerText);
    	mysql_checkFieldStructure('participants','id_num','int(11)','null','NO','key','PRI','extra','auto_increment');
    	mysql_checkFieldStructure('participants','name','varchar(32)','null','NO','key','UNI');
    	mysql_checkFieldStructure('participants','last_update','timestamp','null','NO','default','CURRENT_TIMESTAMP','extra','on update CURRENT_TIMESTAMP');
    	mysql_checkFieldStructure('participants','creation_date','datetime','null','NO','default','1900-01-01 00:00:00');
    	mysql_checkFieldStructure('participants','notes','mediumtext','creationText','ALTER TABLE participants ADD notes MEDIUMTEXT');
        mysql_checkFieldStructure('participants','private_comments','mediumtext','creationText','ALTER TABLE participants ADD private_comments MEDIUMTEXT');
    catch
        rethrow(lasterror) %nothing more to add
    end

end